package com.sdp.khy.baotou.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.khy.baotou.cache.clean.KhyCleanCache;
import com.sdp.khy.baotou.db.khy_coupon_scheme.entity.KhyCouponScheme;
import com.sdp.khy.baotou.db.khy_coupon_scheme.service.IKhyCouponSchemeService;
import com.sdp.khy.baotou.db.khy_coupon_scheme_user.entity.KhyCouponSchemeUser;
import com.sdp.khy.baotou.db.khy_coupon_scheme_user.service.IKhyCouponSchemeUserService;
import com.sdp.khy.baotou.db.khy_user.entity.KhyUser;
import com.sdp.khy.baotou.db.khy_user.service.IKhyUserService;
import com.sdp.khy.baotou.db.khy_user_coupon.entity.KhyUserCoupon;
import com.sdp.khy.baotou.db.khy_user_coupon.service.IKhyUserCouponService;
import com.sdp.khy.baotou.utils.KhyConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/KhyCouponSchemeController")
public class KhyCouponSchemeController {
    @Autowired
    private Query query;
    @Autowired
    private UniqueCheckTools uniqueCheckTools;
    @Autowired
    private KhyCleanCache khyCleanCache;
    @Autowired
    private IKhyUserService iKhyUserService;
    @Autowired
    private IKhyCouponSchemeService iKhyCouponSchemeService;
    @Autowired
    private IKhyCouponSchemeUserService iKhyCouponSchemeUserService;
    @Autowired
    private IKhyUserCouponService iKhyUserCouponService;


    @PostMapping(value = "/page")
    public Result<?> page(@RequestBody DataCenter dataCenter) {
        return Result.ok(query.page(iKhyCouponSchemeService, KhyCouponScheme.class, dataCenter));
    }
    @PostMapping(value = "/save")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> save(@RequestBody KhyCouponScheme khyCouponScheme) {
        if(khyCouponScheme==null) {
            return Result.error("优惠卷信息为空");
        }
        if(StringUtils.isEmpty(khyCouponScheme.getKeyId())) {
            Result<?> r = uniqueCheckTools.isUniqueSingle(iKhyCouponSchemeService, KhyCouponScheme.class, new String[] {"couponName"}, "keyId", khyCouponScheme, null, false);
            if(r==null || !r.isSuccess()) {
                return Result.error("优惠卷名称不能重复");
            }

            iKhyCouponSchemeService.save(khyCouponScheme);
        }else {
            Result<?> r = uniqueCheckTools.isUniqueSingle(iKhyCouponSchemeService, KhyCouponScheme.class, new String[] {"couponName"}, "keyId", null, khyCouponScheme, false);
            if(r==null || !r.isSuccess()) {
                return Result.error("优惠卷名称不能重复");
            }
            iKhyCouponSchemeService.updateById(khyCouponScheme);
        }
        khyCleanCache.cleanBusCache();
        return Result.ok();
    }
    @PostMapping(value = "/saveData")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> save(@RequestBody JSONObject data) {
        KhyCouponScheme khyCouponScheme = data.getObject("formData", KhyCouponScheme.class);
        List<KhyCouponSchemeUser> khyCouponSchemeUserList = JSONObject.parseArray(JSON.toJSONString(data.get("recordList")), KhyCouponSchemeUser.class);
        if(khyCouponScheme==null) {
            return Result.error("优惠卷信息为空");
        }
        if(KhyConstants.是.getCode().equals(khyCouponScheme.getGenerateStatus())){
            return Result.error("已经生成优惠卷，信息不能进行修改");
        }
        if(StringUtils.isEmpty(khyCouponScheme.getKeyId())) {
            Result<?> r = uniqueCheckTools.isUniqueSingle(iKhyCouponSchemeService, KhyCouponScheme.class, new String[] {"couponName"}, "keyId", khyCouponScheme, null, false);
            if(r==null || !r.isSuccess()) {
                return Result.error("优惠卷名称不能重复");
            }
            khyCouponScheme.setGenerateStatus(KhyConstants.否.getCode());
            iKhyCouponSchemeService.save(khyCouponScheme);
        }else {
            Result<?> r = uniqueCheckTools.isUniqueSingle(iKhyCouponSchemeService, KhyCouponScheme.class, new String[] {"couponName"}, "keyId", null, khyCouponScheme, false);
            if(r==null || !r.isSuccess()) {
                return Result.error("优惠卷名称不能重复");
            }
            iKhyCouponSchemeService.updateById(khyCouponScheme);
        }
        // 先删除旧优惠卷
        QueryWrapper<KhyCouponSchemeUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(KhyCouponSchemeUser::getSchemeId,khyCouponScheme.getKeyId());
        iKhyCouponSchemeUserService.remove(queryWrapper);
        // 如果是全部发放，则查询所有注册用户
        if(KhyConstants.全体用户.getCode().equals(khyCouponScheme.getApplyType())){
        List<KhyUser> khyUserList=iKhyUserService.list();
        if(khyUserList.size()>0){
            List<KhyCouponSchemeUser> insertKhyCouponSchemeUserList=new ArrayList<>();
            for(KhyUser khyUser:khyUserList){
                KhyCouponSchemeUser khyCouponSchemeUser=new KhyCouponSchemeUser();
                khyCouponSchemeUser.setSchemeId(khyCouponScheme.getKeyId());
                khyCouponSchemeUser.setUserNo(khyUser.getUserNo());
                insertKhyCouponSchemeUserList.add(khyCouponSchemeUser);
            }
            iKhyCouponSchemeUserService.saveBatch(insertKhyCouponSchemeUserList);
          }
        }else {
            if (khyCouponSchemeUserList.size() > 0) {
                for (KhyCouponSchemeUser khyCouponSchemeUser : khyCouponSchemeUserList) {
                    khyCouponSchemeUser.setSchemeId(khyCouponScheme.getKeyId());
                }
            }
            iKhyCouponSchemeUserService.saveBatch(khyCouponSchemeUserList);
        }
        return Result.ok();
    }
    @GetMapping(value = "/createGenerate")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> createGenerate(@RequestParam(name="keyId",required=true) String keyId) {
        if(StringUtils.isEmpty(keyId)) {
            return Result.error("优惠方案不存在");
        }
        QueryWrapper<KhyCouponScheme> khyCouponSchemeQueryWrapper=new QueryWrapper<>();
        khyCouponSchemeQueryWrapper.lambda().eq(KhyCouponScheme::getKeyId,keyId);
        KhyCouponScheme khyCouponScheme=iKhyCouponSchemeService.getOne(khyCouponSchemeQueryWrapper,false);
        if(khyCouponScheme == null){
            return Result.error("优惠方案不存在");
        }
        //存在按照配置生成优惠卷
        // 查询用户
        QueryWrapper<KhyCouponSchemeUser> khyCouponSchemeUserQueryWrapper=new QueryWrapper<>();
        khyCouponSchemeUserQueryWrapper.lambda().eq(KhyCouponSchemeUser::getSchemeId,khyCouponScheme.getKeyId());
        List<KhyCouponSchemeUser> khyCouponSchemeUserList=iKhyCouponSchemeUserService.list(khyCouponSchemeUserQueryWrapper);
        if(!StringUtils.isEmpty(khyCouponScheme.getPerCount())){
            List<KhyUserCoupon> insertKhyUserCouponList=new ArrayList<>();
            for(int i=0;i<Integer.parseInt(khyCouponScheme.getPerCount());i++){
                for(KhyCouponSchemeUser khyCouponSchemeUser:khyCouponSchemeUserList){
                    KhyUserCoupon khyUserCoupon=new KhyUserCoupon();
                    khyUserCoupon.setCouponName(khyCouponScheme.getCouponName());
                    khyUserCoupon.setCouponStatus(KhyConstants.是.getCode());
                    khyUserCoupon.setCouponType(khyCouponScheme.getCouponType());
                    khyUserCoupon.setCouponValue(khyCouponScheme.getCouponValue());
                    khyUserCoupon.setCreateTime(LocalDateTime.now());
                    khyUserCoupon.setSchemeId(khyCouponScheme.getKeyId());
                    khyUserCoupon.setUserNo(khyCouponSchemeUser.getUserNo());
                    khyUserCoupon.setEndDate(khyCouponScheme.getEndDate());
                    insertKhyUserCouponList.add(khyUserCoupon);;
                }
            }
            iKhyUserCouponService.saveBatch(insertKhyUserCouponList);
            khyCouponScheme.setGenerateStatus(KhyConstants.是.getCode());
            iKhyCouponSchemeService.updateById(khyCouponScheme);
        }
        return Result.ok();
    }
}
